package com.fand.stater.handler;

import java.nio.charset.Charset;
import java.util.Date;

import javax.annotation.Resource;

import cn.hutool.core.date.DateUtil;
import com.fand.stater.constant.EventCodeEnum;
import com.fand.stater.constant.FandIndexConstant;
import com.fand.stater.constant.RocketTopicConstant;
import com.fand.stater.model.es.SysUserESIndexRecord;
import com.fand.common.util.JsonUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.lucene.util.QueryBuilder;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.index.reindex.DeleteByQueryRequest;

/**
 * Author: zhangjiabin
 * Email: javaboyok@163.com
 * CreateDate: 2021/6/26
 * Version: 1.0
 */
@Slf4j
public class SysUserESIndexRecordHandler {

    @Resource
    private DefaultMQProducer producer;

    @Resource
    private RestHighLevelClient restHighLevelClient;

    @SneakyThrows
    public void sendRecord(SysUserESIndexRecord sysUserESIndexRecord) {
        log.info("将用户登录记录报存在es中，用户id:{},用户名称:{},用户编码:{}", sysUserESIndexRecord.getUserId(), sysUserESIndexRecord.getUserName(), sysUserESIndexRecord.getUserCode());
        Message message = new Message(RocketTopicConstant.SYS_USER_COLLECTION_RECORD_TOPIC, "SysUserESIndexRecordListenter", JsonUtils.objectToJson(sysUserESIndexRecord).getBytes(Charset.defaultCharset()));
        producer.send(message, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                log.info("send success,topic:{},msg:{}", RocketTopicConstant.SYS_USER_COLLECTION_RECORD_TOPIC, sysUserESIndexRecord);
            }

            @Override
            public void onException(Throwable e) {
                log.error("send error,topic:{},msg:{}", RocketTopicConstant.SYS_USER_COLLECTION_RECORD_TOPIC, sysUserESIndexRecord, e);
            }
        });
        log.info("rocket send end!");
    }

    @SneakyThrows
    public void insertRecord2Es(String recode) {
        SysUserESIndexRecord sysUserESIndexRecord = JsonUtils.jsonToPojo(recode, SysUserESIndexRecord.class);

        if (EventCodeEnum.INDEX.getCode().equals(sysUserESIndexRecord.getEventCode())) {
            DeleteByQueryRequest deleteRequest = new DeleteByQueryRequest(FandIndexConstant.FAND_USER_COLLECTION_RECORD);
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
            boolQueryBuilder.must(QueryBuilders.termQuery("userId", sysUserESIndexRecord.getUserId()));
            boolQueryBuilder.must(QueryBuilders.termQuery("eventCode.keyword", EventCodeEnum.INDEX.getCode()));
            deleteRequest.setQuery(boolQueryBuilder);
            restHighLevelClient.deleteByQuery(deleteRequest, RequestOptions.DEFAULT);
        }

        IndexRequest indexRequest = new IndexRequest(FandIndexConstant.FAND_USER_COLLECTION_RECORD);
        indexRequest.source(recode, XContentType.JSON);
        IndexResponse index = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
        int status = index.status().getStatus();
        log.info("插入es返回状态:{},recode:{}", status, recode);
    }

}
